package com.stellar.pay.core.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;


/**
 * @Author Jqcc
 * @Version 1.0
 * @Data 2025/4/4
 * @Description : 基于Redis的幂等请求检测工具类 - 分布式环境下的幂等控制
 */
public class RedisIdempotentRequestChecker {

    private final StringRedisTemplate redisTemplate;

    private final long defaultExpireTime;

    public RedisIdempotentRequestChecker(StringRedisTemplate redisTemplate, long defaultExpireTime) {
        this.redisTemplate = redisTemplate;
        this.defaultExpireTime = defaultExpireTime;
    }

    /**
     * 检查是否为重复请求
     */
    public boolean isDuplicateRequest(String key) {
        return isDuplicateRequest(key, defaultExpireTime);
    }

    /**
     * 检查是否为重复请求
     */
    public boolean isDuplicateRequest(String key, long expireTime) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        Boolean isAbsent = ops.setIfAbsent(key, "1", expireTime, TimeUnit.MILLISECONDS);
        return isAbsent != null && !isAbsent;
    }

    /**
     * 清除请求记录
     */
    public void clearRequest(String key) {
        redisTemplate.delete(key);
    }
}